package cn.edu.mju.user.service.impl;

import cn.edu.mju.common.entity.pojo.UserInfo;
import cn.edu.mju.common.entity.pojo.VipInfo;
import cn.edu.mju.user.mapper.UserInfoMapper;
import cn.edu.mju.user.mapper.VipInfoMapper;
import cn.edu.mju.user.service.IUserInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author 16423
 */
@Service

public class UserInfoServiceImpl implements IUserInfoService {

    private final UserInfoMapper userInfoMapper;
    private final VipInfoMapper vipInfoMapper;

    @Value("${minio.endpoint}")
    private String endpoint;
    @Value("${minio.bucket}")
    private String bucket;

    @Autowired
    public UserInfoServiceImpl(UserInfoMapper userInfoMapper, VipInfoMapper vipInfoMapper) {
        this.userInfoMapper = userInfoMapper;
        this.vipInfoMapper = vipInfoMapper;
    }

    //查询所有用户信息
    @Override
    public List<UserInfo> getAllUser() {

        return userInfoMapper.selectList(null);

    }

    //查询个人信息
    @Override
    public UserInfo getUserInfo(String userId) {

        LambdaQueryWrapper<UserInfo> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UserInfo::getUserId, userId);
        lqw.eq(UserInfo::getStatus, 1);
        return userInfoMapper.selectOne(lqw);

    }

    //修改密码
    @Override
    public boolean updateUserPwd(UserInfo userInfo) {

        if (userInfo.getPassword().isEmpty()) {
            return false;
        }
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        String enPassword = encoder.encode(userInfo.getPassword());

        userInfo.setPassword(enPassword);

        LambdaUpdateWrapper<UserInfo> luw = new LambdaUpdateWrapper<>();
        luw.eq(UserInfo::getUserId, userInfo.getUserId());


        int count = userInfoMapper.update(userInfo, luw);

        return count != 0;


    }

    //逻辑控制用户
    @Override
    public boolean logicRemove(String userId) {

        LambdaUpdateWrapper<UserInfo> luw = new LambdaUpdateWrapper<>();
        luw.eq(UserInfo::getUserId, userId);


        UserInfo checkUser = userInfoMapper.selectOne(luw);
        //非法用户
        if (checkUser == null) {
            return false;
        }

        //检查用户状态是否删除
        if (checkUser.getStatus() == 1) {
            checkUser.setStatus(0);
            int count = userInfoMapper.update(checkUser, luw);
            return count > 0;
        } else {
            checkUser.setStatus(1);
            int count = userInfoMapper.update(checkUser, luw);
            return count > 0;
        }
    }

    //物理删除用户
    @Override
    public boolean physicallyRemove(String userId) {
        LambdaQueryWrapper<UserInfo> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UserInfo::getUserId, userId);

        int count = userInfoMapper.delete(lqw);
        return count > 0;
    }


    //注册
    @Override
    public boolean register(UserInfo userInfo) {

        String format = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        LocalDateTime joinDateTime = LocalDateTime.parse(format, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        ZoneId zoneId = ZoneId.systemDefault();
        Date joinDate = Date.from(joinDateTime.atZone(zoneId).toInstant());

        userInfo.setJoinTime(joinDate);

        userInfo.setUserId(UUID.randomUUID().toString());
        userInfo.setUserAuth("user");

        String uuidString = UUID.randomUUID().toString().replace("-", ""); // 去掉连字符
        String truncatedUUID = uuidString.substring(0, 8); // 截取指定长度
        userInfo.setUserName("用户" + truncatedUUID);

        PasswordEncoder encoder = new BCryptPasswordEncoder();
        userInfo.setPassword(encoder.encode(userInfo.getPassword()));

        userInfo.setAvatar(endpoint + "/" + bucket + "/default.png");

        try {
            int count = userInfoMapper.insert(userInfo);

            VipInfo vipInfo = new VipInfo();
            vipInfo.setUserId(userInfo.getUserId());
            vipInfo.setVipId(UUID.randomUUID().toString());
            vipInfo.setExpTime(new Date());
            vipInfo.setLevelId(1);
            int insert = vipInfoMapper.insert(vipInfo);

            return count > 0 && insert > 0;
        } catch (Exception e) {
            return false;
        }

    }


    //修改信息
    @Override
    public boolean updateUserInfo(UserInfo userInfo) {
        LambdaUpdateWrapper<UserInfo> luw = new LambdaUpdateWrapper<>();
        luw.eq(UserInfo::getUserId, userInfo.getUserId());
        int count = userInfoMapper.update(userInfo, luw);
        return count > 0;
    }

    //获取可用空间
    public Long getUserSpace(String userId) {
        LambdaQueryWrapper<UserInfo> lqw = new LambdaQueryWrapper<>();
        lqw.select(UserInfo::getUserSpace, UserInfo::getTotalSpace);
        lqw.eq(UserInfo::getUserId, userId);
        UserInfo userInfo = userInfoMapper.selectOne(lqw);
        Long userSpace = userInfo.getUserSpace();
        Long totalSpace = userInfo.getTotalSpace();
        return totalSpace - userSpace;

    }
}
